package cmd

import (
	"fmt"
	"path"
	"time"

	"cloudstation/store"
	"cloudstation/store/provider/aliyun"
	"cloudstation/store/provider/miniop"
	"cloudstation/util"

	"github.com/spf13/cobra"
)

const (
	// BuckName todo
	AldefaultBuckName = "testbucket-c1"
	AldefaultEndpoint = "http://oss-cn-beijing.aliyuncs.com"
	AldefaultALIAK    = "LTAI5tKLn5yEtHrGmum28cQe"
	AldefaultALISK    = ""
)

const (
	// BuckName todo
	MinidefaultBuckName = "mymusic"
	MinidefaultEndpoint = "192.168.102.246:9000"
	MinidefaultALIAK    = "AKIAIOSFODNN7EXAMPLE"
	MinidefaultALISK    = ""
)

var (
	buckName       string
	uploadFilePath string
	bucketEndpoint string
)

// uploadCmd represents the start command
var uploadCmd = &cobra.Command{
	Use:   "upload",
	Short: "上传到文件中转站",
	Long:  "上传到文件中转站",
	RunE: func(cmd *cobra.Command, args []string) error {
		p, err := getProvider()
		if err != nil {
			return err
		}
		if uploadFilePath == "" {
			return fmt.Errorf("upload file path is missing")
		}
		day := time.Now().Format("20060102")
		fn := path.Base(uploadFilePath)
		ok := fmt.Sprintf("%s/%s", day, fn)
		err = p.UploadFile(buckName, ok, uploadFilePath)
		if err != nil {
			return err
		}
		return nil
	},
}

func getProvider() (p store.Uploader, err error) {
	switch ossProvider {
	case "aliyun":
		if buckName == "" {
			buckName = AldefaultBuckName
		}
		if bucketEndpoint == "" {
			bucketEndpoint = AldefaultEndpoint
		}
		if AccessID == "" {
			AccessID = AldefaultALIAK
		}
		fmt.Printf("上传云商: 阿里云[%s]\n", bucketEndpoint)
		fmt.Printf("上传用户: %s\n", AccessID)
		util.GetAccessKeyFromInputV2(&AccessKey)
		return aliyun.NewUploader(bucketEndpoint, AccessID, AccessKey)

	case "minio":
		if buckName == "" {
			buckName = MinidefaultBuckName
		}
		if bucketEndpoint == "" {
			bucketEndpoint = MinidefaultEndpoint
		}
		if AccessID == "" {
			AccessID = MinidefaultALIAK
		}
		fmt.Printf("上传云商: MiNIO[%s]\n", bucketEndpoint)

		fmt.Printf("上传用户: %s\n", AccessID)
		util.GetAccessKeyFromInputV2(&AccessKey)
		return miniop.NewUploader(bucketEndpoint, AccessID, AccessKey)

	default:
		return nil, fmt.Errorf("unknown oss privier options [aliyun/minio]")
	}
}

func init() {
	uploadCmd.PersistentFlags().StringVarP(&uploadFilePath, "file_path", "f", "", "upload file path")
	uploadCmd.PersistentFlags().StringVarP(&buckName, "bucket_name", "b", "", "upload oss bucket name")
	uploadCmd.PersistentFlags().StringVarP(&bucketEndpoint, "bucket_endpoint", "e", "", "upload oss endpoint")
	RootCmd.AddCommand(uploadCmd)
}
